import React, { PureComponent } from 'react';
import { Table,Avatar,Button,Modal} from 'antd';
import {Map, Marker, NavigationControl,MapTypeControl,ScaleControl,OverviewMapControl, InfoWindow,TrafficLayer,Road} from 'react-bmap'  ;
import styles from './index.less';
const msgFrom = ["微信","app","平台发布"];
const msgStatus = ["待审","已审待播","已审已播","导播忽略","主播忽略"]

class MsgHisTable extends PureComponent {
  state = {
    selectedRowKeys: [],
    totalCallNo: 0,
    msgHisData:[],
    audioSrc:"",
    videoSrc:"",
    imageSrc:"",
    msgId:"",
    playbackRate:1.0,
    videoVisible: false,
    iamgeVisible:false,
    bmapVisible:false,
    radioValue:1.0,
    curPositionCoor:[],
    curPositionName:"",
  };

  componentWillReceiveProps(nextProps) {
    const { msgHisData: {errorCode,msg,data:{pageNo,pageCount,total,pageSize,list}}, loading } = nextProps;
    this.setState({
      msgHisData:list
    });
    if (nextProps.selectedRows.length === 0) {
      this.setState({
        selectedRowKeys: [],
        totalCallNo: 0,
      });
    }
  }

  //选中的时候处理选中的id
  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    const totalCallNo = selectedRows.reduce((sum, val) => {
      return sum + parseFloat(val.callNo, 10);
    }, 0);

    if (this.props.onSelectRow) {
      this.props.onSelectRow(selectedRows);
    }
    this.setState({ selectedRowKeys, totalCallNo });
  }

  //table分页、排序、筛选变化时触发
  handleTableChange = (pagination, filters, sorter) => {
    this.props.onChange(pagination, filters, sorter);
  }

  delMsgHis = (record,index) => {
    this.props.delMsgHis(record,index);
    /*const msgHisData = this.state.msgHisData;
    msgHisData.splice(index,1);
    this.setState({
      msgHisData:msgHisData.concat([])
    });*/
  }

  delMsgHiss = () => {
    const selectedRowKeys = this.state.selectedRowKeys;
    const ids = selectedRowKeys.toString();
    this.props.delMsgHiss(ids);
  }

  handleGenerateTitle= (total) => {
   return (
     <div>
          <Button type="danger" onClick={()=>this.delMsgHiss()}>删除</Button>
          <span style={{marginLeft:20}}>全部历史消息（{total}）</span>
     </div>
   );
  }


  //主播/导播点击播放音乐按钮
  handleMusicPlay = (id,msgAttSrc) => {
    const radioValue = this.state.radioValue;
    var audio = this.refs.audioMusicPlay;
    const msgId = this.state.msgId;
    //设置好id和src
    this.setState({
      msgId:id,
      audioSrc:msgAttSrc
    });
    audio.playbackRate = radioValue;
    //如果ID不相等，一定是播放，如果ID相等则取反
    //true 指示音频/视频已暂停
    if(msgId != id){
      audio.play();
      if(playPromise === undefined){

      }
    }else {
      if(audio.paused){
        var playPromise = audio.play();
        if(playPromise === undefined){

        }
      }else{
        audio.pause();
      }
    }
    event.stopPropagation();
  }

  handleMoviePlay = (id,msgAttSrc) => {
    var audio = this.refs.audioMusicPlay;
    //如果音乐没有关，先关闭
    if(!audio.paused){
      audio.pause();
    }
    this.setState({
      msgId:id,
      videoSrc:msgAttSrc,
      videoVisible:true
    });
    event.stopPropagation();
  }
  handleImagePlay = (imageSrc) => {
    this.setState({
      imageSrc:imageSrc,
      iamgeVisible:true
    });
    event.stopPropagation();
  }
  //关闭视频Modal
  handleCancelVideoModal= () => {
    var video = this.refs.videoMoviePlay;
    video.pause();
    this.setState({
      videoVisible:false
    });
  }
  //关闭图片Modal
  handleCancelImageModal= () => {
    this.setState({
      iamgeVisible:false
    });
  }

  generateContentDiv = (record) => {
    /*文本内容*/
    if(record.msgContentType == 0){
      return (
        <div style={{marginLeft:12}}>
          {record.msgAttachmentAddr}
        </div>
      );
      /*语音内容*/
    }else if(record.msgContentType == 1){
      return (
        <div style={{marginLeft:12}}>
          <div onClick={() => this.handleMusicPlay(record.id,record.msgAttachmentAddr)} style={{ float:"left", height:26,width:135,backgroundImage:"url("+require("../../../../public/audioImage.png")+")",cursor:"pointer" }}>
            <img src={require("../../../../public/audioImage3.png")} style={{marginLeft:10, height:26,width:26}}/>
          </div>
          <div style={{float:"left",marginTop:3}}>{record.radioLen}"</div>
        </div>
      );
      /*图片内容*/
    } else if(record.msgContentType == 2){
      console.log("imageSRC:"+record.msgAttachmentAddr);
      return (
        <div style={{marginLeft:12}}>
          <img src={record.msgAttachmentAddr} style={{width:60,height:60,marginLeft:0,cursor:"pointer" }}  onClick={() => this.handleImagePlay(record.msgAttachmentAddr) } />
        </div>
      );
      /*视频内容*/
    }else if(record.msgContentType == 4){
      return (
        <div style={{marginLeft:12}}>
          <div >
            <img src={require("../../../../public/video.png")} style={{marginLeft:5, height:32,width:32,cursor:"pointer" }} onClick={() => this.handleMoviePlay(record.id,record.msgAttachmentAddr)} />
          </div>
        </div>
      );
    }

  }

  //关闭地图显示
  handleCancelBMapModal= () => {
    this.setState({
      bmapVisible:false
    });
  }
  //关闭图片Modal
  handleBMapShow= (positionCoor,positionName) => {
    const curPositionCoor = positionCoor.split(",");
    this.setState({
      curPositionCoor:curPositionCoor,
      curPositionName:positionName,

    });
    this.setState({
      bmapVisible:true
    });
  }
  render() {
    const { selectedRowKeys,msgHisData,audioSrc,videoSrc,imageSrc,videoVisible,iamgeVisible,curPositionCoor,curPositionName,bmapVisible } = this.state;
    const { msgHisData: {errorCode,msg,data:{pageNo,pageCount,total,pageSize,list}}, loadingHis } = this.props;

    const columns = [
      {
        title: '用户',
        dataIndex: 'nickname',
        render:(text, record, index) => (
          <div>
            <div>
              <Avatar style={{ verticalAlign: 'middle' }} src={record.headimgurl} />
              <span style={{ marginLeft: 6, verticalAlign: 'middle' }} >
                  {text}
              </span>
            </div>
            <div>
              <span style={{ marginLeft: 6, verticalAlign: 'middle' }} >
                  来自{msgFrom[record.messageFrom]}
              </span>
            </div>
          </div>
        )
      },
      {
        title: '消息内容',
        dataIndex: 'msgAttachmentAddr',
        render:(text, record, index) => (
          this.generateContentDiv(record)
        )
      },
      {
        title: '自动翻译',
        dataIndex: 'msgTxtContent',
      },

      {
        title: '发送位置',
        dataIndex: 'positionCoor',
        render:(text, record, index) => (
          <div><a onClick={() => this.handleBMapShow(record.positionCoor,record.positionName)}>[查看地图]</a></div>
        )
      },

      {
        title: '发送时间',
        dataIndex: 'msgTime',
      },

      {
        title: '审核人',
        dataIndex: 'auditUserName',
      },
      {
        title: '播报主播',
        dataIndex: 'playUserName',
      },
      {
        title: '消息状态',
        dataIndex: 'status',
        render:(text, record, index) => (
          <div>{msgStatus[record.status]} </div>
        )
      },
      {
        title: '操作',
        render: (text,record,index) => (
          <div>
            <a onClick={()=>this.delMsgHis(record,index)}>删除</a>
          </div>
        ),
      },
    ];

    const paginationProps = {
      pageSize:pageSize,
      total:total,
      current:pageNo,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
    };

    return (
      <div className={styles.msgTable}>
        <Table
          title={() => this.handleGenerateTitle(total)}
          loading={loadingHis}
          rowKey={record => record.id}
          rowSelection={rowSelection}
          dataSource={msgHisData}
          columns={columns}
          pagination={paginationProps}
          onChange={this.handleTableChange}
        />
        <div>
          {/* 音乐播放组件*/}
          <audio ref="audioMusicPlay"
                 style={{display:"none"}}
                 src={audioSrc}
                 preload={"auto"}
          >
            {/* <source src={audioSrc} type="audio/ogg"></source>
              <source src={audioSrc} type="audio/mpeg" ></source>*/}
            您当前的浏览器不支持该播放控件
          </audio>
          {/* 视频播放组件*/}
          <Modal
            visible={videoVisible}
            maskClosable={true}
            footer={null}
            onCancel={this.handleCancelVideoModal}
            width={560}
          >
            <video controls="controls" ref="videoMoviePlay"  style={{width:512,height:488}}>
              <source  src={videoSrc}  type="video/mp4" />
              您的浏览器不支持 video 标签。
            </video>
          </Modal>
          <Modal
            visible={iamgeVisible}
            footer={null}
            onCancel={this.handleCancelImageModal}>
            <img alt="example" style={{ width: '100%' }} src={imageSrc} />
          </Modal>
          {/*地图插件*/}
          <Modal
            visible={bmapVisible}
            maskClosable={true}
            footer={null}
            onCancel={this.handleCancelBMapModal}
            width={888}
          >
            <Map center={{lng: curPositionCoor[0],lat: curPositionCoor[1]}} zoom="18" >
              <Marker position={{lng: curPositionCoor[0],lat: curPositionCoor[1]}} />
              <NavigationControl />
              <MapTypeControl />
              <ScaleControl />
              <OverviewMapControl />
              <InfoWindow position={{lng: curPositionCoor[0],lat: curPositionCoor[1]}} text={curPositionName} title=""/>
            </Map>
          </Modal>
        </div>
      </div>
    );
  }
}

export default MsgHisTable;
